"""
项目启动文件

提供简单的命令行界面来运行Agent
"""
import asyncio
import sys
from agentscope.message import Msg
from loguru import logger

from settings import settings
from agents.clients.react_agent_client import ReActAgentClient
from agents.tools.toolkit_manager import ToolkitManager
from agents.mcp.client import MCPClientManager


async def initialize_agent():
    """初始化Agent系统"""
    logger.info("=" * 60)
    logger.info("AgentScope ReActAgent 启动中...")
    logger.info("=" * 60)
    
    # 检查API密钥
    if not settings.DASHSCOPE_API_KEY:
        logger.error("错误：未配置DASHSCOPE_API_KEY")
        logger.info("请在 .env 文件中配置您的API密钥")
        sys.exit(1)
    
    logger.info(f"模型: {settings.QWEN_MODEL_NAME}")
    logger.info(f"Agent: {settings.AGENT_NAME}")
    logger.info(f"长期记忆: {'启用' if settings.ENABLE_LONG_TERM_MEMORY else '禁用'}")
    logger.info("=" * 60)
    
    # 创建工具集
    logger.info("\n初始化工具集...")
    toolkit_manager = ToolkitManager()
    toolkit_manager.register_custom_tools()
    logger.info(f"已注册 {toolkit_manager.get_tool_count()} 个工具")
    
    # 注册MCP工具（如果配置）
    if settings.MCP_SERVER_URL:
        logger.info("\n连接MCP服务器...")
        try:
            mcp_client = MCPClientManager(
                name="mcp_service",
                url=settings.MCP_SERVER_URL,
                transport=settings.MCP_TRANSPORT,
                stateful=False
            )
            await toolkit_manager.register_mcp_client(
                mcp_client.get_client(),
                group_name="mcp_tools"
            )
            logger.info(f"MCP工具已注册，总工具数: {toolkit_manager.get_tool_count()}")
        except Exception as e:
            logger.warning(f"MCP连接失败（将继续使用本地工具）: {e}")
    
    # 创建Agent
    logger.info("\n创建Agent客户端...")
    agent_client = ReActAgentClient(
        username="用户",
        toolkit_manager=toolkit_manager
    )
    
    # 显示可用工具
    tools = toolkit_manager.list_tools()
    logger.info(f"\n可用工具: {', '.join(tools)}")
    
    logger.info("\n" + "=" * 60)
    logger.info("初始化完成！")
    logger.info("=" * 60)
    
    return agent_client


async def chat_loop(agent_client: ReActAgentClient):
    """交互式对话循环"""
    messages = []
    
    print("\n💬 开始对话（输入 'exit' 或 'quit' 退出，输入 'clear' 清空历史）\n")
    
    while True:
        try:
            # 获取用户输入
            user_input = input("你: ").strip()
            
            if not user_input:
                continue
            
            # 退出命令
            if user_input.lower() in ['exit', 'quit', '退出']:
                print("\n再见！👋\n")
                break
            
            # 清空历史命令
            if user_input.lower() in ['clear', '清空']:
                messages = []
                await agent_client.reset_agent_state()
                print("\n历史已清空 ✓\n")
                continue
            
            # 状态查询命令
            if user_input.lower() in ['state', 'status', '状态']:
                state = await agent_client.get_state()
                print(f"\nAgent状态:")
                print(f"  名称: {state.agent_name}")
                print(f"  工具数: {state.tool_count}")
                print(f"  记忆数: {state.memory_size}")
                print(f"  长期记忆: {'启用' if state.long_term_memory_enabled else '禁用'}")
                print()
                continue
            
            # 添加用户消息
            messages.append(Msg(name="用户", content=user_input, role="user"))
            
            # 获取Agent响应
            print(f"\n{settings.AGENT_NAME}: ", end="", flush=True)
            
            assistant_response = ""
            async for response in agent_client.chat_stream(messages):
                if response.code == 200:
                    content = response.content
                    
                    if content.type == "text" and content.text:
                        print(content.text, end="", flush=True)
                        assistant_response += content.text
                    
                    elif content.type == "tool_use" and content.tool_use_name:
                        tools_used = content.tool_use_name.split(",")
                        if len(tools_used) > 1:
                            print(f"\n  🔧 [并行调用: {', '.join(tools_used)}]", end="", flush=True)
                        else:
                            print(f"\n  🔧 [调用工具: {content.tool_use_name}]", end="", flush=True)
                    
                    elif content.type == "thinking" and content.thinking:
                        print(f"\n  💭 [思考中...]", end="", flush=True)
                
                else:
                    print(f"\n❌ 错误: {response.content.error}")
                    break
            
            print("\n")
            
            # 添加助手响应到历史
            if assistant_response:
                messages.append(Msg(name=settings.AGENT_NAME, content=assistant_response, role="assistant"))
        
        except KeyboardInterrupt:
            print("\n\n再见！👋\n")
            break
        except Exception as e:
            logger.error(f"对话错误: {e}")
            print(f"\n❌ 发生错误: {str(e)}\n")


async def main():
    """主函数"""
    try:
        # 初始化Agent
        agent_client = await initialize_agent()
        
        # 启动对话循环
        await chat_loop(agent_client)
    
    except Exception as e:
        logger.error(f"程序错误: {e}")
        sys.exit(1)


if __name__ == "__main__":
    # 运行程序
    asyncio.run(main())
